<template>
  <view class="container">
    <!-- 用户信息 -->
    <view class="user-info" v-if="userInfo">
      <view class="avatar">{{ userInfo.nickname ? userInfo.nickname.charAt(0) : '用' }}</view>
      <view class="user-detail">
        <text class="username">{{ userInfo.nickname || '用户' }}</text>
        <text class="user-phone">{{ userInfo.phone || '' }}</text>
      </view>
      <view class="logout-btn" @tap="handleLogout">
        <text class="logout-text">退出登录</text>
      </view>
    </view>

    <!-- 扫描登录区域 -->
    <view class="scan-section">
      <view class="section-title">Web端登录</view>
      <view class="scan-btn" @tap="scanWebQRCode">
        <text class="scan-icon">📱</text>
        <text class="scan-text">扫描Web端二维码登录</text>
      </view>
      <view class="scan-desc">打开电脑端登录页面，扫描二维码即可登录</view>
    </view>

    <view class="scan-section">
      <view class="section-title">添加设备</view>
      <view class="scan-btn" @click="bind_id">
        <text class="scan-icon">📱</text>
        <text class="scan-text">扫描设备二维码添加设备</text>
      </view>
      <view class="scan-desc">扫描设备二维码获得设备id即可绑定设备</view>
    </view>

<!-- 我的设备区域 -->
<view class="my-devices-section">
  <view class="section-header" @click="toggleDeviceList">
    <text class="section-title">我的设备</text>
    <text class="section-arrow">{{ showDeviceList ? '▲' : '▼' }}</text>
  </view>

  <view class="device-list" v-if="showDeviceList">
    <view v-if="my_devices.length === 0" class="empty-device">
      <text>暂无设备，请先添加设备</text>
    </view>

    <uni-swipe-action>
      <uni-swipe-action-item 
        v-for="(device, index) in my_devices" 
        :key="device.id" 
        :right-options="swipeOptions"
        :auto-close="false"
        @click="handleSwipeClick($event, device.id)">
        <view class="device-item">
          <text class="device-icon">📱</text>
          <text class="device-id">设备ID: {{ device.id }}</text>
          <text class="device-status">
            添加时间:{{ device.createdTime}}
          </text>
        </view>
      </uni-swipe-action-item>
    </uni-swipe-action>
  </view>
</view>
  </view>
</template>

<script>
  import {
    getWxLoginCode
  } from '../../utils/auth.js'
  import {
    get_user_devicedId,deviced_add,deviced_delete
  } from "../../api/device_control";

  import {
    checkAndRefreshToken,
    clearLoginInfo,
    createAuthHeader
  } from "../../utils/request";
  import request from '../../utils/request'

  export default {
    data() {
      return {
        userInfo: null,
        isBluetoothConnected: false,
        // qrString: 'DEMO-' + Date.now(),
        my_devices: [], // 我的设备列表
        showDeviceList: false, // 是否显示设备列表
        swipeOptions: [{
          text: '移除',
          style: {
            backgroundColor: '#ff4757'
          }
        }],
         openedSwipeItem: null // 记录当前打开的滑动项
      }
    },

    onLoad() {
      this.loadUserInfo()
      // 从本地存储加载设备列表
      this.loadDeviceList()
      
      this.get_user_devicedId()
      

    },
    

    onShow() {
      checkAndRefreshToken()
    },

    methods: {
      // 加载用户信息
      loadUserInfo() {
        try {
          const userInfo = uni.getStorageSync('userInfo')
          const accessToken = uni.getStorageSync('accessToken')
          const accessExpiresIn = Number(uni.getStorageSync('accessExpiresIn'))
          const currentTime = Date.now()

          // 检查是否有用户信息、有效token且未过期
          if (userInfo && accessToken && accessExpiresIn && currentTime < accessExpiresIn) {
            this.userInfo = userInfo
          } else {
            // 清除无效的登录信息
            clearLoginInfo()
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }
        } catch (e) {
          console.error('加载用户信息失败:', e)
        }
      },

      // 从本地存储加载设备列表
      loadDeviceList() {
        try {
          const devices = uni.getStorageSync('my_devices')
          if (devices) {
            this.my_devices = devices
          }
        } catch (e) {
          console.error('加载设备列表失败:', e)
        }
      },
      
      //获取用户设备列表
      async get_user_devicedId(){
        const result= await get_user_devicedId()
        if (result.message === 'ok') {
          this.my_devices = result.data
        }
      },


      // 切换设备列表显示/隐藏
      toggleDeviceList() {
        this.showDeviceList = !this.showDeviceList
      },

      // 处理滑动项点击
      handleSwipeClick(e, deviceId) {
        if (e.index === 0) { // 移除按钮
          this.confirmRemoveDevice(deviceId)
        }
      },


  // 确认移除设备
  confirmRemoveDevice(deviceId) {
    uni.showModal({
      title: '移除设备',
      content: `确定要移除设备 ${deviceId} 吗？`,
      confirmText: '移除',
      cancelText: '取消',
      success: async(r) => {
        if (r.confirm) {  
          const result = await deviced_delete(deviceId)
          console.log(result)
          if (result.message === 'ok') {
            this.get_user_devicedId()
            // 移除成功后重置滑动状态
            this.openedSwipeItem = null
            uni.showToast({
              title: '设备已移除',
              icon: 'success'
            })
          }
        }
      }
    })
  },


      handleLogout() {
        uni.showModal({
          title: '确认退出',
          content: '确定要退出当前登录吗？',
          confirmText: '退出',
          cancelText: '取消',
          success: async (res) => {
            if (res.confirm) {
              this.isLogoutLoading = true // 显示加载
              try {
                const logoutRes = await logout()

                if (logoutRes.code === 0) {
                  //  清除本地登录信息
                  clearLoginInfo()
                  //  重置页面数据
                  this.userInfo = null
                  this.isBluetoothConnected = false
                  this.connectedDevice = null
                  //  关闭所有页面跳登录页（避免返回）
                  uni.reLaunch({
                    url: '/pages/login/login'
                  })
                  //  提示成功
                  uni.showToast({
                    title: logoutRes.message || '退出登录成功',
                    icon: 'success'
                  })
                } else {
                  // 接口返回失败（如token无效），仍清除本地信息并跳转
                  throw new Error(logoutRes.message || '退出登录失败')
                }
              } catch (error) {
                // 接口请求失败（如网络错误），兜底处理
                console.error('退出登录失败:', error)
                clearLoginInfo()
                uni.reLaunch({
                  url: '/pages/login/login'
                })
                uni.showToast({
                  title: error.message || '退出失败，请重试',
                  icon: 'none'
                })
              } finally {
                this.isLogoutLoading = false
              }
            }
          }
        })
      },

      // 扫描Web端二维码
      async scanWebQRCode() {
        const accessToken = uni.getStorageSync('accessToken')
        try {
          const loginCode = await getWxLoginCode()
          // 调用微信原生扫码API
          uni.scanCode({
            onlyFromCamera: true,
            scanType: ['qrCode'],
            success: async (scanRes) => {
              uni.showModal({
                title: '确认登录',
                content: '是否允许使用当前账号登录Web端？',
                confirmText: '确认登录',
                cancelText: '取消',
                success: async (modalRes) => {
                  if (modalRes.confirm) {
                    this.isScanLoading = true
                    try {
                      const qrScanRes = await scanLogin(scanRes.result, loginCode)
                      if (qrScanRes.code === 0) {
                        uni.showToast({
                          title: '登录确认成功，Web端即将登录',
                          icon: 'success'
                        })
                      } else if (qrScanRes.code === 50003) {
                        uni.showToast({
                          title: '二维码已过期，请刷新Web端二维码',
                          icon: 'none'
                        })
                      } else if (qrScanRes.code === 40900) {
                        uni.showToast({
                          title: '重复扫码二维码',
                          icon: 'none'
                        })
                      } else {
                        uni.showToast({
                          title: '登录失败，请重试',
                          icon: 'none'
                        })
                      }
                    } catch (error) {
                      uni.showToast({
                        title: error.message || '登录失败，请重试',
                        icon: 'none'
                      })
                    } finally {
                      this.isScanLoading = false
                    }
                  } else {
                    // 用户取消登录
                    uni.showToast({
                      title: '已取消登录',
                      icon: 'none'
                    })
                  }
                }
              })
            },
            fail: (err) => {
              if (err.errMsg !== 'scanCode:fail cancel') {
                uni.showToast({
                  title: '扫码失败，请重试',
                  icon: 'none'
                })
              }
            }
          })
        } catch (error) {
          uni.showToast({
            title: '获取登录凭证失败',
            icon: 'none'
          })
        }
      },

//添加设备
      async bind_id() {
        uni.scanCode({
          onlyFromCamera: true,
          scanType: ['qrCode'],
          success: async (res) => {
            console.log('扫描结果:', res.result)
            uni.showModal({
              title: '绑定设备',
              content: `确定要添加设备 ${res.result} 吗？`,
              confirmText: '确定',
              cancelText: '取消',
              success: async(r) => {
                if (r.confirm) {  
                   const result = await deviced_add(res.result)
                   console.log(result)
                   if (result.message === 'ok') {
                     this.get_user_devicedId()
                     uni.showToast({
                       title: '设备绑定成功',
                       icon: 'success'
                     })
                   }
                   if (result.message === '设备不存在') {
                     uni.$showMsg('该设备不存在')
                   }
                   if (result.message === '设备已绑定') {
                     uni.$showMsg('该设备已被绑定')
                   }
                }
              }
            })
          },
          fail: (err) => {
            uni.showToast({
              title: '扫码失败',
              icon: 'none'
            })
          }
        })
      },


    },
  }
</script>

<style scoped>
  .container {
    padding: 30rpx;
    min-height: 100vh;
    background: #f5f5f5;
  }

  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: white;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    background: #1b9a7c;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    font-weight: bold;
  }

  .user-detail {
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .username {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .user-phone {
    font-size: 24rpx;
    color: #666;
  }

  .logout-btn {
    padding: 12rpx 24rpx;
    background: #fef0f0;
    color: #f56c6c;
    border-radius: 12rpx;
    font-size: 24rpx;
  }

  .logout-text {
    font-weight: 500;
  }

  .scan-section {
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: white;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .section-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .scan-btn {
    background: linear-gradient(135deg, #1b9a7c, #2daf8b);
    color: white;
    border: none;
    border-radius: 15rpx;
    padding: 25rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    margin-bottom: 15rpx;
  }

  .scan-icon {
    font-size: 40rpx;
    margin-right: 15rpx;
  }

  .scan-desc {
    font-size: 24rpx;
    color: #666;
    text-align: center;
    margin-bottom: 30rpx;
  }

  /* 我的设备区域样式 */
  .my-devices-section {
    margin-bottom: 40rpx;
    padding: 30rpx;
    background: white;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eee;
  }

  .section-arrow {
    font-size: 28rpx;
    color: #666;
  }

  .device-list {
    margin-top: 20rpx;
  }

  .empty-device {
    padding: 40rpx 0;
    text-align: center;
    color: #999;
    font-size: 26rpx;
  }

  .device-item {
    display: flex;
    align-items: center;
    padding: 25rpx;
    background: #f8f9fa;
    border-radius: 10rpx;
    margin-bottom: 15rpx;
  }

  .device-icon {
    font-size: 40rpx;
    margin-right: 20rpx;
  }

  .device-id {
    flex: 1;
    font-size: 26rpx;
    color: #333;
  }

  .device-status {
    font-size: 24rpx;
    /* color: #1b9a7c; */
    padding: 6rpx 12rpx;
    border-radius: 12rpx;
    /* background: #f0f0f0; */
  }



  /* 滑动操作按钮样式 */
  .uni-swipe-button {
    border-radius: 10rpx;
  }
</style>